package com.fatiny.core.db;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.fatiny.core.common.Config;
import com.fatiny.core.db.po.Entity;
import com.fatiny.util.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 封装一个实体名, 以及属性信息
 * 
 * @auth Jeremy
 * @date 2019年9月16日上午10:56:00
 */
public class ExcelEntity extends Entity<ExcelProperties> {

	private String tablName; // 表名
	private List<String> primaryKeys;// 主键
	private Map<String, ExcelAssistEntity> assistEntityMap; //辅助字段

	public ExcelEntity() {
		super();
		this.primaryKeys = Lists.newArrayList();
		this.assistEntityMap = Maps.newLinkedHashMap();
	}

	public ExcelEntity(String entityName) {
		super(entityName);
		this.primaryKeys = Lists.newArrayList();
		this.assistEntityMap = Maps.newLinkedHashMap();
	}
	
	@Override
	public void setEntityName(String entityName) {
		super.setEntityName(entityName);
	}

	public String getTablName() {
		if (org.apache.commons.lang3.StringUtils.isBlank(tablName)) {
			this.tablName = StringUtils.humpToUnderline(entityName);
		}
		return tablName;
	}

	public void setTablName(String tablName) {
		this.tablName = tablName;
	}
	
	public void addAssistEntity(String assistName, ExcelAssistProperties prop) {
		ExcelAssistEntity ent = assistEntityMap.get(assistName);
		if (ent == null) {
			ent = new ExcelAssistEntity(assistName);
			assistEntityMap.put(assistName, ent);
		}
		ent.addEntityBeans(prop);
	}
	
	public Map<String, ExcelAssistEntity> getAssistEntityMap() {
		return assistEntityMap;
	}

	public String getPrimary() {
		StringBuilder sb = new StringBuilder();
		for (String primary : primaryKeys) {
			sb.append("`").append(primary).append("`").append(",");
		}
		if (sb.length() > 1) {
			sb.deleteCharAt(sb.length() - 1);
		}
		return sb.toString();
	}

	public List<String> getPrimaryKeys() {
		return primaryKeys;
	}

	public void setPrimaryKeys(List<String> primaryKeys) {
		this.primaryKeys = primaryKeys;
	}

	/**
	 * 设置主键
	 */
	public void setPrimarys(List<String> primarys) {
		int index = 0;
		for (String primary : primarys) {
			for (ExcelProperties excelBean : entityBeans) {
				if (excelBean.getField().equals(primary)) {
					++index;
					excelBean.setPrimary(String.valueOf(index));
				}
			}
		}
		this.primaryKeys = primarys;
	}

	@Override
	public String toString() {
		return "ExcelEntity [entityName=" + entityName + ", entityBeans=" + entityBeans +", assistEntityMap="+assistEntityMap+ "]";
	}

	/**
	 * 生成toSting方法
	 * 
	 * @return
	 * @return String
	 * @date 2019年9月16日上午10:25:13
	 */
	public String getToStr() {
		StringBuilder builder = new StringBuilder();
		builder.append("\"").append(entityName);
		//builder.append("[ playerId= \" +getPlayerId()+ \"+");
		int length = 0;
		for (ExcelProperties excelBean : entityBeans) {
			length++;
//			if (length == 1) {
//				builder.append(" [");
//			}else {
			builder.append(", ");
//			}
			builder.append(excelBean.getField()).append("= \"+ ").append(excelBean.getField());
			if (length % 5 == 0) {
				builder.append("\n\t\t\t\t");
			}
			if (length == entityBeans.size()) {
				builder.append("+\"]\";");
			} else {
				builder.append(" +\"");
			}
		}
		return builder.toString();
	}

	/**
	 * 生成主键
	 */
	public String getPrimaryKey() {
		Map<Integer, ExcelProperties> primaryMap = null;
		try {
			primaryMap = new TreeMap<Integer, ExcelProperties>();
			for (ExcelProperties excelBean : entityBeans) {
				if (excelBean.getPrimary() == null)
					continue;
				int primary = Integer.parseInt(excelBean.getPrimary());
				if (primary > 0) {
					primaryMap.put(primary, excelBean);
				}
			}
			if (primaryMap.isEmpty())
				throw new RuntimeException("请设置主键!, entityName:" + entityName);

			StringBuilder builder = new StringBuilder();
			String plus = "+\"-\"+";
			for (ExcelProperties excelBean : primaryMap.values()) {
				builder.append(excelBean.getField());
				builder.append(plus);
			}
			int start = builder.length() - plus.length();
			builder.delete(start, builder.length());
			return builder.toString();
		} catch (Exception e) {
			throw new RuntimeException("生成主键异常, entityName:" + entityName + ", primaryMap:" + primaryMap, e);
		}
	}

//	/**
//	 * 生成数据库字段
//	 * 
//	 * @return
//	 */
//	public String getFileds() {
//		StringBuilder builder = new StringBuilder();
//		for (ExcelProperties excelBean : entityBeans) {
//			builder.append(excelBean.getTbField()).append(",");
//		}
//		builder.deleteCharAt(builder.length() - 1);
//		return builder.toString();
//	}

	/**
	 * java字段
	 * 
	 * @return
	 */
	public String getJavaFiled() {
		StringBuilder builder = new StringBuilder();
		for (ExcelProperties excelBean : entityBeans) {
			builder.append(":ei.").append(excelBean.getField()).append(",");
		}
		builder.deleteCharAt(builder.length() - 1);
		return builder.toString();
	}

//	//
//	/**
//	 * 生成修改语句
//	 * 
//	 * @return @SQL("UPDATE "+TABLE+" SET
//	 *         PlayerId=:ei.playerId,ConfigId=:ei.configId,Level=:ei.level,Exp=:ei.exp,RefineLv=:ei.refineLv,SkillLv=:ei.skillLv,State=:ei.state,HolySealLv=:ei.holySealLv,SkinId=:ei.skinId,MissionStr=:ei.missionStr,UsedMaterial=:ei.usedMaterial
//	 *         WHERE PlayerId=:ei.playerId and ConfigId=:ei.configId") public int
//	 *         update(@SQLParam("ei") Artifact data);
//	 */
//	public String getUpdateSql() {
//		StringBuilder builder = new StringBuilder("UPDATE \"+TABLE+\" SET ");
//		for (ExcelProperties excelBean : entityBeans) {
//			builder.append(excelBean.getTbField()).append("=:ei.").append(excelBean.getField()).append(",");
//		}
//		builder.deleteCharAt(builder.length() - 1);
//		// 拼接where, primaryKeys
//		builder.append(" WHERE ");
//		for (String primary : primaryKeys) {
//			builder.append(primary).append("=:ei.").append(StringUtils.firstCharLower(primary)).append(" and ");
//		}
//		builder.delete(builder.length() - 5, builder.length());
////		builder.append("\")");
////		//换行方法
////		builder.append("\n");
////		builder.append("public int update(").append("@SQLParam(\"ei\") ").append(entityName).append(" data);");
//
//		return builder.toString();
//	}

	/**
	 * 生成insert语句
	 * 
	 * @return INSERT INTO "+TABLE+" ("+FIELD+")
	 *         VALUES(:ei.playerId,:ei.configId,:ei.level,:ei.exp,:ei.refineLv,:ei.skillLv,:ei.state,:ei.holySealLv,:ei.skinId,:ei.missionStr,:ei.usedMaterial)
	 */
	public String getInsertSql() {
		StringBuilder builder = new StringBuilder("INSERT INTO \"+TABLE+\" (\"+FIELD+\") VALUES(");
		for (ExcelProperties excelBean : entityBeans) {
			builder.append(":ei.").append(excelBean.getField()).append(",");
		}
		builder.deleteCharAt(builder.length() - 1);
		builder.append(")");
		return builder.toString();
	}

	/**
	 * 生成delete语句
	 * 
	 * @return delete from "+TABLE+" WHERE PlayerId=:ei.playerId
	 */
	public String getDeleteSql() {
		StringBuilder builder = new StringBuilder("delete from \"+TABLE+\" WHERE ");
		for (String primary : primaryKeys) {
			builder.append(primary).append("=:ei.").append(StringUtils.firstCharLower(primary)).append(" and ");
		}
		builder.deleteCharAt(builder.length() - 5);
		return builder.toString();
	}

	/**
	 * 生成delete语句
	 * 
	 * @return delete from "+TABLE+" WHERE PlayerId=:ei.playerId
	 */
	public String getDeleteAllSql() {
		StringBuilder builder = new StringBuilder("delete from \"+TABLE+\" WHERE ");
		for (String primary : primaryKeys) {
			builder.append(primary).append("=:ei.").append(StringUtils.firstCharLower(primary));
			break;
		}
		return builder.toString();
	}

	/**
	 * 生成select语句
	 * 
	 * @return SELECT "+FIELD+" FROM "+TABLE+" WHERE playerId= :playerId limit 1
	 */
	public String getSelectOneSql() {
		StringBuilder builder = new StringBuilder(" SELECT \"+FIELD+\" FROM \"+TABLE+\" WHERE ");
		for (String primary : primaryKeys) {
			builder.append(primary).append("=:ei.").append(StringUtils.firstCharLower(primary)).append(" and ");
		}
		builder.deleteCharAt(builder.length() - 5);
		return builder.toString();
	}

	/**
	 * 生成selectMore语句
	 * 
	 * @return SELECT "+FIELD+" FROM "+TABLE+" WHERE playerId= :playerId limit 1
	 */
	public String getSelectMoreSql() {
		StringBuilder builder = new StringBuilder(" SELECT \"+FIELD+\" FROM \"+TABLE+\" WHERE ");
		for (String primary : primaryKeys) {
			builder.append(primary).append("=:ei.").append(StringUtils.firstCharLower(primary));
			break;
		}
		return builder.toString();
	}
	
	public String getModuleName() {
		return Config.genTbMap.get(this.entityName).getModuleName();
	}

}
